
function animate(obj,target){
    clearInterval(obj.timer)
    obj.timer = setInterval(function(){ //每隔一段时间执行代码
        const step = Math.floor((target - obj.offsetLeft) / 10); //offsetleft获取左侧偏移量
        if(obj.offsetLeft === target){
            clearInterval(obj.timer);    //停止setInterval()
        }
        obj.style.left = obj.offsetLeft + step +'px';
    },30);
}

window.addEventListener('load',function(){
    let circle;
    let num;
    const left = document.querySelector('.left');
    const right = document.querySelector('.right');
    const box = document.querySelector('.container');
    box.addEventListener('mouseenter',function(){
        left.style.display = 'block';
        right.style.display = 'block';
    })
    box.addEventListener('mouseleave',function(){
        left.style.display = 'none';
        right.style.display = 'none';
    })
    const pic = document.querySelector('.pic');
    const lis = document.querySelector('.lis');
    const boxWidth = box.offsetWidth;
    for(let i = 0; i<pic.children.length; i++){

        const li = document.createElement('li');
        lis.appendChild(li);
        //设置索引号
        li.setAttribute('index',i);
        li.addEventListener('click',function(){
            //获得索引号
            const index = this.getAttribute('index');
            num = index;
            circle = index;
            for(let i = 0; i<lis.children.length; i++){
                lis.children[i].className = '';
            }
            this.className = 'selected';
            animate(pic,-index*boxWidth)
        })
    }
    lis.children[0].className = 'selected';

    //克隆第一个li
    const first = pic.children[0].cloneNode(true);
    pic.appendChild(first);
    num = 0;
    circle = 0;

    //右侧按钮的功能
    right.addEventListener('click',function(){
        if(num === pic.children.length-1){
            pic.style.left = 0;
            num = 0;
        }
        num++;
        animate(pic,-num*boxWidth);
        circle++;
        if(circle === lis.children.length){
            circle = 0;
        }
        for(let i =0; i<lis.children.length; i++){
            lis.children[i].className = '';
        }
        lis.children[circle].className = 'selected';
    })

    //左侧按钮功能
    left.addEventListener('click',function(){
        if(num === 0){
            num = pic.children.length-1;
            pic.style.left = -num*boxWidth+'px';

        }
        num--;
        animate(pic,-num*boxWidth);
        circle--;
        if(circle <0){
            circle = lis.children.length-1;
        }
        for(let i =0; i<lis.children.length; i++){
            lis.children[i].className = '';
        }
        lis.children[circle].className = 'selected';
    })
    this.setInterval(function () {
        right.click();
    }, 2000);
})